// 全局配置
const CONFIG = {
    TOAST_DURATION: 3000,
    ANIMATION_DURATION: 300,
    CHART_COLORS: {
        primary: '#667eea',
        secondary: '#764ba2',
        success: '#48bb78',
        warning: '#ecc94b',
        danger: '#f56565',
        info: '#4299e1'
    },
    UPDATE_INTERVAL: 30000 // 系统信息更新间隔 (30秒)
};

// 工具函数
const utils = {
    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    formatDate(date) {
        return new Date(date).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    },

    debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    },

    generateId() {
        return '_' + Math.random().toString(36).substr(2, 9);
    }
};

// UI 组件
const UI = {
    toast: {
        show(message, type = 'info') {
            const toast = document.createElement('div');
            toast.className = `toast ${type} animate-fade-in-up`;
            toast.innerHTML = `
                <div class="flex items-center">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'} mr-2"></i>
                    ${message}
                </div>
            `;
            document.body.appendChild(toast);
            setTimeout(() => {
                toast.classList.add('animate-fade-out-down');
                setTimeout(() => toast.remove(), 300);
            }, 3000);
        }
    },

    modal: {
        show(content) {
            const modalId = utils.generateId();
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.id = modalId;
            modal.innerHTML = `
                <div class="modal-content">
                    <button class="absolute top-4 right-4 text-gray-500 hover:text-gray-700">
                        <i class="fas fa-times"></i>
                    </button>
                    ${content}
                </div>
            `;

            document.getElementById('modal-container').appendChild(modal);
            setTimeout(() => modal.classList.add('active'), 10);

            const closeBtn = modal.querySelector('button');
            closeBtn.addEventListener('click', () => this.close(modalId));

            return modalId;
        },

        close(modalId) {
            const modal = document.getElementById(modalId);
            if (modal) {
                modal.classList.remove('active');
                setTimeout(() => modal.remove(), CONFIG.ANIMATION_DURATION);
            }
        }
    },

    loading: {
        show() {
            document.getElementById('loading-overlay').classList.remove('hidden');
            document.getElementById('loading-overlay').classList.add('flex');
        },
        hide() {
            document.getElementById('loading-overlay').classList.add('hidden');
            document.getElementById('loading-overlay').classList.remove('flex');
        }
    }
};

// 文件管理
const FileManager = {
    init() {
        this.initDropZone();
        this.initFileList();
        this.initSearch();
        this.initSort();
        this.initBatchOperations();
    },

    initDropZone() {
        const dropZone = document.querySelector('.drop-zone');
        const fileInput = document.getElementById('file');
        const uploadForm = document.getElementById('uploadForm');
        const progressBar = document.querySelector('.progress-bar');

        if (!dropZone || !fileInput || !uploadForm) return;

        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, this.preventDefaults, false);
        });

        ['dragenter', 'dragover'].forEach(eventName => {
            dropZone.addEventListener(eventName, () => this.highlight(dropZone), false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropZone.addEventListener(eventName, () => this.unhighlight(dropZone), false);
        });

        dropZone.addEventListener('drop', (e) => this.handleDrop(e, fileInput), false);
        fileInput.addEventListener('change', () => this.handleFiles(fileInput.files), false);
    },

    preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    },

    highlight(element) {
        element.classList.add('border-primary', 'bg-primary-50');
    },

    unhighlight(element) {
        element.classList.remove('border-primary', 'bg-primary-50');
    },

    handleDrop(e, fileInput) {
        const dt = e.dataTransfer;
        fileInput.files = dt.files;
        this.handleFiles(dt.files);
    },

    handleFiles(files) {
        if (files.length === 0) return;

        const formData = new FormData();
        let totalSize = 0;
        const file = files[0]; // 只取第一个文件，不支持多文件上传
        
        if (this.validateFile(file)) {
            totalSize = file.size;
            
            const maxSize = 1024 * 1024 * 1024; // 1GB limit
            if (totalSize > maxSize) {
                UI.toast.show('文件大小超过限制', 'error');
                return;
            }
            
            formData.append('file', file);
            this.uploadFiles(formData);
        }
    },

    validateFile(file) {
        // 检查文件扩展名
        const fileName = file.name;
        const fileExt = fileName.split('.').pop().toLowerCase();
        const allowedExts = ['txt', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];
        
        // 允许的MIME类型
        const allowedTypes = [
            'text/plain',
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-powerpoint',
            'application/vnd.openxmlformats-officedocument.presentationml.presentation'
        ];
        
        // 有些浏览器可能不正确检测Office文件的MIME类型，因此同时检查扩展名
        if (!allowedExts.includes(fileExt) && !allowedTypes.includes(file.type)) {
            UI.toast.show(`不支持的文件类型: ${file.name}`, 'error');
            return false;
        }

        const maxSize = 1024 * 1024 * 1024; // 1GB
        if (file.size > maxSize) {
            UI.toast.show(`文件过大，最大支持1GB: ${file.name}`, 'error');
            return false;
        }

        return true;
    },

    async uploadFiles(formData) {
        UI.loading.show();
        const progressBar = document.querySelector('.progress-bar');
        const uploadStatus = document.getElementById('upload-status');
        const uploadPercentage = document.getElementById('upload-percentage');
        const uploadSpeed = document.getElementById('upload-speed');
        const uploadRemaining = document.getElementById('upload-remaining');

        try {
            const xhr = new XMLHttpRequest();
            const startTime = Date.now();
            
            // 设置进度监听
            xhr.upload.onprogress = (e) => {
                if (e.lengthComputable) {
                    const percentComplete = (e.loaded / e.total) * 100;
                    const timeElapsed = (Date.now() - startTime) / 1000; // 已用时间(秒)
                    const speed = e.loaded / timeElapsed; // 字节/秒
                    const remaining = (e.total - e.loaded) / speed; // 剩余时间(秒)
                    
                    // 更新进度条
                    progressBar.style.width = percentComplete + '%';
                    uploadPercentage.textContent = Math.round(percentComplete) + '%';
                    
                    // 更新状态文本
                    uploadStatus.textContent = '正在上传文件...';
                    
                    // 格式化并显示上传速度
                    let speedText = '';
                    if (speed > 1024 * 1024) { // 大于1MB/s
                        speedText = `${(speed / (1024 * 1024)).toFixed(2)} MB/s`;
                    } else {
                        speedText = `${(speed / 1024).toFixed(2)} KB/s`;
                    }
                    uploadSpeed.textContent = `上传速度: ${speedText}`;
                    
                    // 格式化并显示剩余时间
                    let remainingText = '';
                    if (remaining > 60) {
                        remainingText = `${Math.ceil(remaining / 60)} 分钟`;
                    } else {
                        remainingText = `${Math.ceil(remaining)} 秒`;
                    }
                    uploadRemaining.textContent = `剩余时间: ${remainingText}`;
                }
            };

            // 创建Promise包装XHR请求
            const response = await new Promise((resolve, reject) => {
                xhr.open('POST', '/upload/');
                
                xhr.onload = () => {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        resolve(JSON.parse(xhr.responseText));
                    } else {
                        reject(new Error(`HTTP error! status: ${xhr.status}`));
                    }
                };
                
                xhr.onerror = () => reject(new Error('Network error'));
                xhr.send(formData);
            });

            if (response) {
                uploadStatus.textContent = '上传完成！';
                uploadSpeed.textContent = '上传速度: --';
                uploadRemaining.textContent = '剩余时间: --';
                UI.toast.show('文件上传成功', 'success');
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            }
        } catch (error) {
            console.error('Upload error:', error);
            uploadStatus.textContent = '上传失败';
            UI.toast.show('上传过程中发生错误', 'error');
        } finally {
            UI.loading.hide();
            if (progressBar) {
                progressBar.style.width = '0%';
            }
            const fileInput = document.getElementById('file');
            if (fileInput) {
                fileInput.value = '';
            }
        }
    },

    initFileList() {
        this.initFileActions();
        this.initInfiniteScroll();
    },

    initFileActions() {
        document.querySelectorAll('.file-action').forEach(button => {
            button.addEventListener('click', (e) => {
                const action = e.currentTarget.dataset.action;
                const fileId = e.currentTarget.dataset.fileId;

                switch (action) {
                    case 'preview':
                        this.previewFile(fileId);
                        break;
                    case 'download':
                        this.downloadFile(fileId);
                        break;
                    case 'delete':
                        this.deleteFile(fileId);
                        break;
                }
            });
        });
    },

    initInfiniteScroll() {
        const fileList = document.querySelector('.file-list');
        if (!fileList) return;

        const observer = new IntersectionObserver(
            (entries) => {
                if (entries[0].isIntersecting) {
                    this.loadMoreFiles();
                }
            },
            { threshold: 0.1 }
        );

        const sentinel = document.createElement('div');
        sentinel.className = 'sentinel';
        fileList.appendChild(sentinel);
        observer.observe(sentinel);
    },

    async loadMoreFiles() {
        const page = (this.currentPage || 1) + 1;
        const response = await fetch(`/documents/list?page=${page}`);
        const data = await response.json();

        if (data.files.length > 0) {
            this.currentPage = page;
            this.renderFiles(data.files);
        }
    },

    renderFiles(files) {
        const template = document.getElementById('file-template');
        const container = document.querySelector('.file-list');

        files.forEach(file => {
            const fileElement = template.content.cloneNode(true);
            // 填充文件信息
            fileElement.querySelector('.file-name').textContent = file.filename;
            fileElement.querySelector('.file-size').textContent = utils.formatFileSize(file.size);
            fileElement.querySelector('.file-date').textContent = utils.formatDate(file.created_at);
            
            // 设置文件类型图标
            const iconElement = fileElement.querySelector('.file-icon');
            iconElement.className = `file-icon ${this.getFileIconClass(file.filename)}`;

            container.appendChild(fileElement);
        });
    },

    getFileIconClass(filename) {
        if (!filename) return 'text-gray-400';
        
        const ext = filename.split('.').pop().toLowerCase();
        const iconMap = {
            pdf: 'text-red-600',
            doc: 'text-blue-600',
            docx: 'text-blue-600',
            xls: 'text-green-600',
            xlsx: 'text-green-600',
            ppt: 'text-orange-600',
            pptx: 'text-orange-600',
            txt: 'text-gray-500',
            jpg: 'text-purple-600',
            jpeg: 'text-purple-600',
            png: 'text-purple-600',
            gif: 'text-purple-600'
        };
        return iconMap[ext] || 'text-gray-400';
    },

    initSearch() {
        const searchInput = document.getElementById('file-search');
        if (!searchInput) return;

        const debouncedSearch = utils.debounce((query) => {
            this.searchFiles(query);
        }, 300);

        searchInput.addEventListener('input', (e) => {
            debouncedSearch(e.target.value);
        });
    },

    async searchFiles(query) {
        if (!query.trim()) {
            // 如果搜索框为空，恢复显示所有文件
            this.refreshFileList();
            return;
        }

        UI.loading.show();
        try {
            const response = await fetch(`/documents/search?q=${encodeURIComponent(query)}`);
            const data = await response.json();
            
            const container = document.querySelector('.divide-y');
            if (!container) return;

            if (data.files.length === 0) {
                container.innerHTML = `
                    <div class="p-4 text-center text-gray-500">
                        未找到匹配的文件
                    </div>
                `;
                return;
            }

            container.innerHTML = data.files.map(file => `
                <div class="file-item p-4 hover:bg-gray-50 transition-colors duration-150">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center space-x-4">
                            <!-- 文件图标 -->
                            <div class="file-icon flex-shrink-0">
                                ${this.getFileIconHtml(file)}
                            </div>
                            
                            <!-- 下载按钮 -->
                            <a href="/documents/download/${file.filename}" class="text-indigo-600 hover:text-indigo-900 flex-shrink-0">
                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
                                </svg>
                            </a>
                            
                            <!-- 文件信息 -->
                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-medium text-gray-900 truncate">
                                    ${file.original_name || file.filename}
                                </p>
                                <div class="flex items-center space-x-4 mt-1">
                                    <p class="text-xs text-gray-500">
                                        <i class="fas fa-clock mr-1"></i>
                                        ${file.upload_time}
                                    </p>
                                    <p class="text-xs text-gray-500">
                                        <i class="fas fa-network-wired mr-1"></i>
                                        ${file.uploader_ip}
                                    </p>
                                    <p class="text-xs text-gray-500">
                                        <i class="fas fa-map-marker-alt mr-1"></i>
                                        ${file.uploader_location}
                                    </p>
                                    <p class="text-xs text-gray-500">
                                        <i class="fas fa-hdd mr-1"></i>
                                        ${(file.size / 1024).toFixed(1)} KB
                                    </p>
                                </div>
                            </div>
                        </div>
                        <!-- 预览按钮 -->
                        <div class="flex items-center space-x-2">
                            ${file.filename.match(/\.(jpg|jpeg|png|gif|pdf)$/i) ? `
                                <button class="text-gray-600 hover:text-gray-900" data-preview="/documents/download/${file.filename}">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                                    </svg>
                                </button>
                            ` : ''}
                        </div>
                    </div>
                </div>
            `).join('');

            // 重新绑定预览按钮事件
            this.initFileActions();
        } catch (error) {
            console.error('Search error:', error);
            UI.toast.show('搜索失败', 'error');
        } finally {
            UI.loading.hide();
        }
    },

    getFileIconHtml(file) {
        const filename = file.filename.toLowerCase();
        if (filename.endsWith('.doc') || filename.endsWith('.docx') || file.file_type === 'word') {
            return '<svg class="w-8 h-8 text-blue-600" fill="currentColor" viewBox="0 0 20 20"><path d="M4 4a2 2 0 012-2h8a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V4z"/></svg>';
        } else if (filename.endsWith('.xls') || filename.endsWith('.xlsx') || file.file_type === 'excel') {
            return '<svg class="w-8 h-8 text-green-600" fill="currentColor" viewBox="0 0 20 20"><path d="M4 4a2 2 0 012-2h8a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V4z"/></svg>';
        } else if (filename.endsWith('.ppt') || filename.endsWith('.pptx') || file.file_type === 'powerpoint') {
            return '<svg class="w-8 h-8 text-orange-600" fill="currentColor" viewBox="0 0 20 20"><path d="M4 4a2 2 0 012-2h8a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V4z"/></svg>';
        } else if (filename.endsWith('.pdf') || file.file_type === 'pdf') {
            return '<svg class="w-8 h-8 text-red-600" fill="currentColor" viewBox="0 0 20 20"><path d="M4 4a2 2 0 012-2h8a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V4z"/></svg>';
        } else if (filename.match(/\.(jpg|jpeg|png|gif)$/i) || file.file_type === 'image') {
            return '<svg class="w-8 h-8 text-purple-600" fill="currentColor" viewBox="0 0 20 20"><path d="M4 4a2 2 0 012-2h8a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V4z"/></svg>';
        } else {
            return '<svg class="w-8 h-8 text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path d="M4 4a2 2 0 012-2h8a2 2 0 012 2v12a2 2 0 01-2 2H6a2 2 0 01-2-2V4z"/></svg>';
        }
    },

    initSort() {
        const sortButtons = document.querySelectorAll('.sort-button');
        sortButtons.forEach(button => {
            button.addEventListener('click', () => {
                const field = button.dataset.field;
                const currentOrder = button.dataset.order || 'asc';
                const newOrder = currentOrder === 'asc' ? 'desc' : 'asc';

                // 更新排序图标
                sortButtons.forEach(btn => {
                    btn.dataset.order = '';
                    btn.querySelector('.sort-icon').className = 'sort-icon text-gray-400';
                });

                button.dataset.order = newOrder;
                button.querySelector('.sort-icon').className = `sort-icon text-primary ${newOrder === 'asc' ? 'transform rotate-180' : ''}`;

                this.sortFiles(field, newOrder);
            });
        });
    },

    async sortFiles(field, order) {
        UI.loading.show();

        try {
            const response = await fetch(`/documents/sort?field=${field}&order=${order}`);
            const data = await response.json();

            const container = document.querySelector('.file-list');
            container.innerHTML = '';
            this.renderFiles(data.files);
        } catch (error) {
            console.error('Sort error:', error);
            UI.toast.show('排序失败', 'error');
        } finally {
            UI.loading.hide();
        }
    },

    initBatchOperations() {
        const selectAllCheckbox = document.getElementById('select-all');
        if (!selectAllCheckbox) return;

        selectAllCheckbox.addEventListener('change', () => {
            const fileCheckboxes = document.querySelectorAll('.file-checkbox');
            fileCheckboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
            });
            this.updateBatchOperationsUI();
        });

        document.querySelectorAll('.file-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', () => {
                this.updateBatchOperationsUI();
            });
        });

        document.getElementById('batch-download')?.addEventListener('click', () => {
            this.batchDownload();
        });

        document.getElementById('batch-delete')?.addEventListener('click', () => {
            this.batchDelete();
        });
    },

    updateBatchOperationsUI() {
        const selectedFiles = document.querySelectorAll('.file-checkbox:checked');
        const batchOperations = document.querySelector('.batch-operations');
        
        if (selectedFiles.length > 0) {
            batchOperations.classList.remove('hidden');
            document.getElementById('selected-count').textContent = selectedFiles.length;
        } else {
            batchOperations.classList.add('hidden');
        }
    },

    async batchDownload() {
        const selectedFiles = Array.from(document.querySelectorAll('.file-checkbox:checked'))
            .map(checkbox => checkbox.value);

        if (selectedFiles.length === 0) return;

        UI.loading.show();

        try {
            const response = await fetch('/documents/batch-download', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ files: selectedFiles })
            });

            if (response.ok) {
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = 'documents.zip';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                a.remove();
            } else {
                throw new Error('Download failed');
            }
        } catch (error) {
            console.error('Batch download error:', error);
            UI.toast.show('批量下载失败', 'error');
        } finally {
            UI.loading.hide();
        }
    },

    async batchDelete() {
        const selectedFiles = Array.from(document.querySelectorAll('.file-checkbox:checked'))
            .map(checkbox => checkbox.value);

        if (selectedFiles.length === 0) return;

        if (!confirm(`确定要删除选中的 ${selectedFiles.length} 个文件吗？`)) return;

        UI.loading.show();

        try {
            const response = await fetch('/documents/batch-delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ files: selectedFiles })
            });

            const result = await response.json();

            if (result.success) {
                UI.toast.show('批量删除成功', 'success');
                this.refreshFileList();
            } else {
                throw new Error(result.message || 'Delete failed');
            }
        } catch (error) {
            console.error('Batch delete error:', error);
            UI.toast.show('批量删除失败', 'error');
        } finally {
            UI.loading.hide();
        }
    },

    async refreshFileList() {
        const response = await fetch('/documents/list');
        const data = await response.json();

        const container = document.querySelector('.file-list');
        container.innerHTML = '';
        this.renderFiles(data.files);
        this.updateStats();
    },

    async updateStats() {
        const response = await fetch('/system/stats');
        const stats = await response.json();

        document.getElementById('total-files').textContent = stats.total_files;
        document.getElementById('total-size').textContent = utils.formatFileSize(stats.total_size);

        this.updateStorageChart(stats);
    },

    updateStorageChart(stats) {
        const chart = echarts.init(document.getElementById('storage-chart'));
        
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c} ({d}%)'
            },
            series: [{
                name: '存储空间',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                label: {
                    show: false,
                    position: 'center'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '20',
                        fontWeight: 'bold'
                    }
                },
                labelLine: {
                    show: false
                },
                data: [
                    { value: stats.total_size, name: '已用空间' },
                    { value: stats.total_capacity - stats.total_size, name: '可用空间' }
                ]
            }]
        };

        chart.setOption(option);
    }
};

// 系统设置
const SystemSettings = {
    init() {
        this.initThemeToggle();
        this.initNotifications();
        this.initUserMenu();
    },

    initThemeToggle() {
        const toggle = document.getElementById('theme-toggle');
        if (!toggle) return;

        // 获取当前主题或默认使用 light
        const currentTheme = localStorage.getItem('theme') || 'light';
        document.documentElement.classList.remove('light', 'dark');
        document.documentElement.classList.add(currentTheme);

        // 更新图标
        this.updateThemeIcon(currentTheme);

        toggle.addEventListener('click', () => {
            const isDark = document.documentElement.classList.contains('dark');
            const newTheme = isDark ? 'light' : 'dark';
            
            document.documentElement.classList.remove('light', 'dark');
            document.documentElement.classList.add(newTheme);
            localStorage.setItem('theme', newTheme);
            
            // 更新图标
            this.updateThemeIcon(newTheme);
        });
    },

    updateThemeIcon(theme) {
        const toggle = document.getElementById('theme-toggle');
        if (!toggle) return;

        // 更新图标
        toggle.innerHTML = theme === 'dark' ? `
            <svg class="w-6 h-6 text-gray-600 dark:text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
            </svg>
        ` : `
            <svg class="w-6 h-6 text-gray-600 dark:text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
            </svg>
        `;
    },

    initNotifications() {
        const toggle = document.getElementById('notifications-toggle');
        const panel = document.getElementById('notifications-panel');
        if (!toggle || !panel) return;

        toggle.addEventListener('click', () => {
            panel.classList.toggle('hidden');
            this.loadNotifications();
        });

        document.addEventListener('click', (e) => {
            if (!panel.contains(e.target) && !toggle.contains(e.target)) {
                panel.classList.add('hidden');
            }
        });
    },

    async loadNotifications() {
        const panel = document.getElementById('notifications-panel');
        
        try {
            const response = await fetch('/system/notifications');
            const data = await response.json();

            panel.innerHTML = data.notifications.map(notification => `
                <div class="p-4 border-b border-gray-200 dark:border-gray-700">
                    <div class="flex items-center">
                        <i class="fas fa-${notification.icon} text-${notification.type}-500 mr-3"></i>
                        <div class="flex-1">
                            <p class="text-sm font-medium text-gray-900 dark:text-gray-100">${notification.title}</p>
                            <p class="text-sm text-gray-500 dark:text-gray-400">${notification.message}</p>
                            <p class="text-xs text-gray-400 dark:text-gray-500 mt-1">${utils.formatDate(notification.time)}</p>
                        </div>
                    </div>
                </div>
            `).join('') || '<div class="p-4 text-center text-gray-500">暂无通知</div>';
        } catch (error) {
            console.error('Load notifications error:', error);
            panel.innerHTML = '<div class="p-4 text-center text-red-500">加载失败</div>';
        }
    },

    initUserMenu() {
        const toggle = document.getElementById('user-menu');
        const dropdown = document.getElementById('user-menu-dropdown');
        if (!toggle || !dropdown) return;

        toggle.addEventListener('click', () => {
            dropdown.classList.toggle('hidden');
        });

        document.addEventListener('click', (e) => {
            if (!dropdown.contains(e.target) && !toggle.contains(e.target)) {
                dropdown.classList.add('hidden');
            }
        });
    }
};

// 系统状态更新
const SystemStatus = {
    init() {
        this.updateUptime();
        // 每秒更新一次运行时间
        setInterval(() => this.updateUptime(), 1000);
    },

    async updateUptime() {
        try {
            const response = await fetch('/system/status');
            const data = await response.json();
            if (data.uptime !== undefined) {
                const uptimeElement = document.querySelector('.system-uptime');
                if (uptimeElement) {
                    const hours = Math.floor(data.uptime / 3600);
                    const minutes = Math.floor((data.uptime % 3600) / 60);
                    const seconds = data.uptime % 60;
                    uptimeElement.textContent = `运行时间: ${hours}时${minutes}分${seconds}秒`;
                }
            }
        } catch (error) {
            console.error('Failed to update uptime:', error);
        }
    }
};

async function showLoginRecords() {
    UI.loading.show();
    try {
        const response = await fetch('/auth/login_records');
        const data = await response.json();
        
        if (data.success) {
            const content = `
                <div class="p-4">
                    <h2 class="text-xl font-bold mb-4">登录记录</h2>
                    <div class="max-h-96 overflow-y-auto">
                        <table class="min-w-full">
                            <thead>
                                <tr class="bg-gray-100 dark:bg-gray-700">
                                    <th class="px-4 py-2 text-left">时间</th>
                                    <th class="px-4 py-2 text-left">IP地址</th>
                                    <th class="px-4 py-2 text-left">主机名</th>
                                    <th class="px-4 py-2 text-left">状态</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${data.records.map(record => `
                                    <tr class="border-b border-gray-200 dark:border-gray-700">
                                        <td class="px-4 py-2">${record.timestamp}</td>
                                        <td class="px-4 py-2">${record.ip}</td>
                                        <td class="px-4 py-2">${record.hostname}</td>
                                        <td class="px-4 py-2">
                                            <span class="px-2 py-1 rounded text-xs ${record.success ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}">
                                                ${record.success ? '成功' : '失败'}
                                            </span>
                                        </td>
                                    </tr>
                                `).join('')}
                            </tbody>
                        </table>
                    </div>
                </div>
            `;
            UI.modal.show(content);
        } else {
            UI.toast.show('获取登录记录失败', 'error');
        }
    } catch (error) {
        console.error('Error fetching login records:', error);
        UI.toast.show('获取登录记录失败', 'error');
    } finally {
        UI.loading.hide();
    }
}

// 系统信息模块
const systemInfo = {
    // 存储CPU和内存历史数据
    cpuHistory: Array(11).fill(0),
    memoryHistory: Array(11).fill(0),
    
    init() {
        // 只在存在系统信息图表元素时初始化
        if (document.getElementById('resource-chart') && document.getElementById('file-type-chart')) {
            this.initResourceChart();
            this.initFileTypeChart();
            this.updateSystemInfo();
            
            // 显示更新间隔
            document.getElementById('update-interval').textContent = CONFIG.UPDATE_INTERVAL / 1000;
            
            // 定时更新系统信息
            setInterval(() => this.updateSystemInfo(), CONFIG.UPDATE_INTERVAL);
            
            // 获取系统事件
            this.fetchSystemEvents();
            setInterval(() => this.fetchSystemEvents(), CONFIG.UPDATE_INTERVAL);
            
            // 手动刷新按钮
            document.getElementById('refresh-system-info')?.addEventListener('click', () => {
                this.updateSystemInfo();
                this.fetchSystemEvents();
                
                // 显示刷新动画
                const refreshBtn = document.getElementById('refresh-system-info');
                refreshBtn.classList.add('animate-spin');
                setTimeout(() => {
                    refreshBtn.classList.remove('animate-spin');
                }, 1000);
                
                // 显示提示消息
                Toast.show('系统信息已刷新', 'success');
            });
        }
    },
    
    // 初始化资源使用率图表 (CPU & 内存)
    initResourceChart() {
        const chartDom = document.getElementById('resource-chart');
        if (!chartDom) return;
        
        const myChart = echarts.init(chartDom);
        this.resourceChart = myChart; // 保存引用以便后续更新
        
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: '#6a7985'
                    }
                }
            },
            legend: {
                data: ['CPU', '内存'],
                textStyle: {
                    color: document.documentElement.classList.contains('dark') ? '#e2e8f0' : '#4a5568'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [
                {
                    type: 'category',
                    boundaryGap: false,
                    data: this.getLast10Minutes(),
                    axisLabel: {
                        color: document.documentElement.classList.contains('dark') ? '#e2e8f0' : '#4a5568'
                    }
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    max: 100,
                    axisLabel: {
                        formatter: '{value}%',
                        color: document.documentElement.classList.contains('dark') ? '#e2e8f0' : '#4a5568'
                    }
                }
            ],
            series: [
                {
                    name: 'CPU',
                    type: 'line',
                    stack: 'Total',
                    smooth: true,
                    lineStyle: {
                        width: 3,
                        color: CONFIG.CHART_COLORS.primary
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(102, 126, 234, 0.5)' },
                            { offset: 1, color: 'rgba(102, 126, 234, 0.1)' }
                        ])
                    },
                    emphasis: {
                        focus: 'series'
                    },
                    data: this.cpuHistory
                },
                {
                    name: '内存',
                    type: 'line',
                    stack: 'Total',
                    smooth: true,
                    lineStyle: {
                        width: 3,
                        color: CONFIG.CHART_COLORS.secondary
                    },
                    areaStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: 'rgba(118, 75, 162, 0.5)' },
                            { offset: 1, color: 'rgba(118, 75, 162, 0.1)' }
                        ])
                    },
                    emphasis: {
                        focus: 'series'
                    },
                    data: this.memoryHistory
                }
            ]
        };
        
        myChart.setOption(option);
        window.addEventListener('resize', () => myChart.resize());
        
        // 主题变化时更新图表
        document.getElementById('theme-toggle')?.addEventListener('click', () => {
            setTimeout(() => {
                myChart.setOption({
                    legend: {
                        textStyle: {
                            color: document.documentElement.classList.contains('dark') ? '#e2e8f0' : '#4a5568'
                        }
                    },
                    xAxis: [{
                        axisLabel: {
                            color: document.documentElement.classList.contains('dark') ? '#e2e8f0' : '#4a5568'
                        }
                    }],
                    yAxis: [{
                        axisLabel: {
                            color: document.documentElement.classList.contains('dark') ? '#e2e8f0' : '#4a5568'
                        }
                    }]
                });
                myChart.resize();
            }, 200);
        });
    },
    
    // 初始化文件类型分布图表
    initFileTypeChart() {
        const chartDom = document.getElementById('file-type-chart');
        if (!chartDom) return;
        
        const myChart = echarts.init(chartDom);
        this.fileTypeChart = myChart; // 保存引用以便后续更新
        
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                right: 10,
                top: 'center',
                data: ['PDF', 'DOC/DOCX', 'XLS/XLSX', 'PPT/PPTX', '其他'],
                textStyle: {
                    color: document.documentElement.classList.contains('dark') ? '#e2e8f0' : '#4a5568'
                }
            },
            series: [
                {
                    name: '文件类型',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '14',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: [
                        { value: 0, name: 'PDF', itemStyle: { color: '#F56565' } },
                        { value: 0, name: 'DOC/DOCX', itemStyle: { color: '#4299E1' } },
                        { value: 0, name: 'XLS/XLSX', itemStyle: { color: '#48BB78' } },
                        { value: 0, name: 'PPT/PPTX', itemStyle: { color: '#ECC94B' } },
                        { value: 0, name: '其他', itemStyle: { color: '#A0AEC0' } }
                    ]
                }
            ]
        };
        
        myChart.setOption(option);
        window.addEventListener('resize', () => myChart.resize());
        
        // 主题变化时更新图表
        document.getElementById('theme-toggle')?.addEventListener('click', () => {
            setTimeout(() => {
                myChart.setOption({
                    legend: {
                        textStyle: {
                            color: document.documentElement.classList.contains('dark') ? '#e2e8f0' : '#4a5568'
                        }
                    }
                });
                myChart.resize();
            }, 200);
        });
    },
    
    // 从后端API获取最新的系统信息
    async updateSystemInfo() {
        try {
            // 获取系统状态
            const statusResponse = await fetch('/system/status');
            if (statusResponse.ok) {
                const statusData = await statusResponse.json();
                this.updateSystemStatus(statusData);
            }
            
            // 获取系统统计信息
            const statsResponse = await fetch('/system/stats');
            if (statsResponse.ok) {
                const statsData = await statsResponse.json();
                this.updateSystemStats(statsData);
            }
            
            // 更新最后刷新时间
            this.updateLastRefreshTime();
        } catch (error) {
            console.error('获取系统信息失败:', error);
        }
    },
    
    // 更新系统状态信息
    updateSystemStatus(data) {
        // 更新系统运行时间
        const uptimeElement = document.querySelector('.system-uptime');
        if (uptimeElement) {
            uptimeElement.textContent = `运行时间: ${data.uptime_formatted}`;
        }
        
        // 更新系统平台信息
        const platformElement = document.getElementById('system-platform');
        if (platformElement && data.system_info) {
            platformElement.textContent = `${data.system_info.platform || '未知'}`;
        }
        
        // 更新系统负载
        const loadElement = document.querySelector('#system-load');
        if (loadElement) {
            loadElement.textContent = data.load.current;
        }
        
        // 更新CPU和内存历史数据
        this.cpuHistory.shift();
        this.cpuHistory.push(data.load.cpu_percent);
        
        this.memoryHistory.shift();
        this.memoryHistory.push(data.memory.percent);
        
        // 更新资源图表
        if (this.resourceChart) {
            this.resourceChart.setOption({
                xAxis: {
                    data: this.getLast10Minutes()
                },
                series: [
                    {
                        name: 'CPU',
                        data: this.cpuHistory
                    },
                    {
                        name: '内存',
                        data: this.memoryHistory
                    }
                ]
            });
        }
    },
    
    // 更新系统统计信息
    updateSystemStats(data) {
        // 更新存储信息
        document.querySelector('#total-storage').textContent = data.storage.total_formatted;
        document.querySelector('#used-storage').textContent = data.storage.used_formatted;
        document.querySelector('#free-storage').textContent = data.storage.free_formatted;
        
        // 更新存储使用率进度条
        const progressBar = document.querySelector('.bg-indigo-600');
        if (progressBar) {
            progressBar.style.width = `${data.storage.percent}%`;
        }
        
        // 更新文件统计信息
        document.querySelector('#total-files').textContent = data.files.total;
        document.querySelector('#total-download').textContent = data.files.total; // 目前没有下载计数，暂用文件总数
        document.querySelector('#upload-today').textContent = data.files.today_uploads;
        document.querySelector('#download-today').textContent = data.files.today_downloads || 0;
        
        // 更新文件类型分布图表
        if (this.fileTypeChart && data.files.file_types) {
            const chartData = data.files.file_types.map(item => {
                return {
                    name: item.name,
                    value: item.value,
                    itemStyle: this.getColorForFileType(item.name)
                };
            });
            
            this.fileTypeChart.setOption({
                series: [{
                    data: chartData
                }]
            });
        }
    },
    
    // 获取文件类型对应的颜色
    getColorForFileType(typeName) {
        const colors = {
            'PDF': { color: '#F56565' },
            'DOC/DOCX': { color: '#4299E1' },
            'XLS/XLSX': { color: '#48BB78' },
            'PPT/PPTX': { color: '#ECC94B' },
            '其他': { color: '#A0AEC0' }
        };
        return colors[typeName] || { color: '#A0AEC0' };
    },
    
    // 获取系统事件
    async fetchSystemEvents() {
        try {
            const response = await fetch('/system/events');
            if (response.ok) {
                const events = await response.json();
                this.updateSystemEvents(events);
            }
        } catch (error) {
            console.error('获取系统事件失败:', error);
        }
    },
    
    // 更新系统事件列表
    updateSystemEvents(events) {
        const eventsContainer = document.getElementById('system-events');
        if (!eventsContainer) return;
        
        eventsContainer.innerHTML = '';
        
        events.forEach(event => {
            const eventElement = document.createElement('div');
            eventElement.className = 'flex items-center space-x-2 text-xs hover:bg-gray-50 dark:hover:bg-gray-700 rounded px-1 py-0.5';
            
            // 根据事件类型选择图标和颜色
            let icon = 'info-circle';
            let color = 'text-gray-500';
            
            switch(event.type) {
                case 'upload':
                    icon = 'upload';
                    color = 'text-green-500';
                    break;
                case 'download':
                    icon = 'download';
                    color = 'text-blue-500';
                    break;
                case 'info':
                    icon = 'info-circle';
                    color = 'text-gray-500';
                    break;
            }
            
            eventElement.innerHTML = `
                <span class="text-gray-400 dark:text-gray-500 whitespace-nowrap">${event.timestamp}</span>
                <i class="fas fa-${icon} ${color}"></i>
                <span class="text-gray-700 dark:text-gray-300 truncate">${event.message}</span>
            `;
            eventsContainer.appendChild(eventElement);
        });
    },
    
    // 生成过去10分钟的时间标签
    getLast10Minutes() {
        const times = [];
        const now = new Date();
        
        for (let i = 10; i >= 0; i--) {
            const time = new Date(now.getTime() - i * 60000);
            times.push(`${time.getHours().toString().padStart(2, '0')}:${time.getMinutes().toString().padStart(2, '0')}`);
        }
        
        return times;
    },
    
    // 更新最后刷新时间
    updateLastRefreshTime() {
        const now = new Date();
        const timeStr = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
        document.getElementById('last-update-time').textContent = timeStr;
    }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // 只在文件管理页面初始化 FileManager
    if (document.querySelector('.file-list') || document.querySelector('.drop-zone')) {
        FileManager.init();
    }

    // 只在有系统设置相关元素时初始化 SystemSettings
    if (document.getElementById('theme-toggle') || document.getElementById('user-menu')) {
        SystemSettings.init();
    }

    // 只在系统状态页面初始化相关功能
    if (document.querySelector('.system-uptime')) {
        SystemStatus.init();
    }

    // 只在系统信息页面初始化
    if (document.getElementById('resource-chart') || document.getElementById('file-type-chart')) {
        systemInfo.init();
    }
    
    // 初始化用户菜单
    const userMenu = document.getElementById('user-menu');
    const userMenuDropdown = document.getElementById('user-menu-dropdown');
    
    if (userMenu && userMenuDropdown) {
        userMenu.addEventListener('click', (e) => {
            e.stopPropagation();
            userMenuDropdown.classList.toggle('hidden');
        });
        
        document.addEventListener('click', (e) => {
            if (!userMenuDropdown.contains(e.target) && !userMenu.contains(e.target)) {
                userMenuDropdown.classList.add('hidden');
            }
        });
    }
}); 